//
//  YeKaRefreshControl.swift
//  YeKa
//
//  Created by Gina on 15/10/18.
//  Copyright © 2015年 Gina. All rights reserved.
//

import UIKit

// 下拉刷心动 偏移量，超出之后，翻转动画。
private let kRefreshPullOffset: CGFloat = -60

// 下拉刷新控件，集成在 TableViewController
class YeKaRefreshControl: UIRefreshControl {

    
    /*
    // KVO 函数
    
    // 向下拉表格。Y越来越小
    // 向上推表格，Y值越来越大
    // 从表格顶部向下拉。Y值是负数。
    // 拽到一定幅度，会自动进入刷新状态。
    
    */
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        if refreshing {
            refreshView.startLoading()
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = true
            
        } else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag{
            refreshView.rotateFlag = false
            
        }
        
        
        
    }
    
    override init() {
        super.init()
        
        setUpUI();
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        NSThread.sleepForTimeInterval(0.5)
        refreshView.stopLoading()
    }
    
    
    private func setUpUI() {
        
        // KVO 监听 frame属性变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        tintColor = UIColor.clearColor()
        addSubview(refreshView)
        // 自动布局
        let x = (UIScreen.mainScreen().bounds.width - refreshView.bounds.width) / 2
        refreshView.frame = CGRectMake(x, 0, refreshView.bounds.width, refreshView.bounds.height)
        
    }
    
    // MARK:    懒加载控件
    private lazy var refreshView: YeKaRefreshView = YeKaRefreshView.refreshView()
    
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }

}



// 下拉刷新视图，负责显示动画
class YeKaRefreshView: UIView {
    
    private var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    @IBOutlet weak var iconView: UIImageView!
    
    @IBOutlet weak var shuaxinView: UIView!
    
    @IBOutlet weak var loadIcon: UIImageView!
    
    
    // 从xib加载刷新视图
    class func refreshView() -> YeKaRefreshView {
        return NSBundle.mainBundle().loadNibNamed("refresh", owner: nil, options: nil).last as! YeKaRefreshView
    }
    
    private func rotateTipIcon() {
        // 在块代码动画中，旋转会就近原则。默认顺时针寻找方向。
        let angle = rotateFlag ? CGFloat(M_PI-0.01) : CGFloat(-M_PI+0.01)
        
        UIView.animateWithDuration(0.5) { () -> Void in
            self.iconView.transform = CGAffineTransformRotate(self.iconView.transform, CGFloat(angle))
        }
        
    }
    
    // 开始加载动画
    private func startLoading() {
        
        if loadIcon.layer.animationForKey("loadingAnim") != nil {
            return
        }
        // 隐藏提示视图
        shuaxinView.hidden = true
        // 定义动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        loadIcon.layer.addAnimation(anim, forKey: "loadingAnim")
    }
    
    // 停止加载动画
    private func stopLoading() {
        shuaxinView.hidden = false
        loadIcon.layer.removeAllAnimations()
    }
    
}